#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
收藏相关API
"""

from flask_restful import Resource, reqparse
from flask import request, current_app, g
from app.services.civil_code_service import civil_code_service
from app.utils.response_utils import create_response
from app.middleware.ip_middleware import get_current_user_id, get_current_user_ip

class FavoriteListAPI(Resource):
    """收藏列表API"""
    
    def get(self):
        """获取收藏列表"""
        try:
            # 解析查询参数
            parser = reqparse.RequestParser()
            parser.add_argument('page', type=int, default=1, help='页码', location='args')
            parser.add_argument('per_page', type=int, default=20, help='每页条数', location='args')
            parser.add_argument('user_id', type=str, required=False, help='用户ID（调试用）', location='args')
            
            args = parser.parse_args()
            
            # 自动从IP中间件获取用户标识，或使用调试参数
            user_id = args.get('user_id') or get_current_user_id()
            current_app.logger.info(f"收藏API获取到的用户ID: {user_id}")
            
            result = civil_code_service.get_user_favorites(
                user_id=user_id,
                page=args['page'],
                per_page=min(args['per_page'], 100)
            )
            current_app.logger.info(f"收藏API返回结果类型: {type(result)}")
            current_app.logger.info(f"收藏API返回结果键: {result.keys() if isinstance(result, dict) else 'Not a dict'}")
            current_app.logger.info(f"收藏数量: {len(result.get('favorites', [])) if isinstance(result, dict) else 'N/A'}")
            current_app.logger.info(f"分页信息: {result.get('pagination', {}) if isinstance(result, dict) else 'N/A'}")
            
            return create_response(
                success=True,
                data=result,
                message="获取收藏列表成功"
            )
            
        except Exception as e:
            current_app.logger.error(f"获取收藏列表失败: {str(e)}")
            import traceback
            current_app.logger.error(f"详细错误信息: {traceback.format_exc()}")
            return create_response(
                success=False,
                error={
                    'code': 'FAVORITES_LIST_ERROR',
                    'message': '获取收藏列表失败',
                    'details': f"错误详情: {str(e)}"  # 临时显示详细错误信息
                },
                status_code=500
            )
    
    def post(self):
        """添加收藏"""
        try:
            # 解析请求数据
            parser = reqparse.RequestParser()
            parser.add_argument('article_number', type=str, required=True, help='条文号不能为空')
            
            args = parser.parse_args()
            
            # 自动从IP中间件获取用户标识
            user_id = get_current_user_id()
            user_ip = get_current_user_ip()
            
            # 添加收藏
            success = civil_code_service.add_favorite(
                user_id=user_id,
                user_ip=user_ip,
                article_number=args['article_number']
            )
            
            if success:
                return create_response(
                    success=True,
                    message=f"收藏法条{args['article_number']}成功"
                )
            else:
                return create_response(
                    success=False,
                    error={
                        'code': 'ARTICLE_NOT_FOUND',
                        'message': f'法条{args["article_number"]}不存在',
                        'details': '请检查条文号是否正确'
                    },
                    status_code=404
                )
                
        except Exception as e:
            current_app.logger.error(f"添加收藏失败: {str(e)}")
            return create_response(
                success=False,
                error={
                    'code': 'ADD_FAVORITE_ERROR',
                    'message': '添加收藏失败',
                    'details': str(e) if current_app.debug else '服务异常'
                },
                status_code=500
            )

class FavoriteAPI(Resource):
    """单个收藏API"""
    
    def delete(self, favorite_id):
        """删除收藏"""
        try:
            # 自动从IP中间件获取用户标识
            user_id = get_current_user_id()
            
            # 删除收藏（这里favorite_id实际是article_number）
            success = civil_code_service.remove_favorite(
                user_id=user_id,
                article_number=favorite_id
            )
            
            if success:
                return create_response(
                    success=True,
                    message=f"移除收藏{favorite_id}成功"
                )
            else:
                return create_response(
                    success=False,
                    error={
                        'code': 'FAVORITE_NOT_FOUND',
                        'message': f'收藏{favorite_id}不存在',
                        'details': '可能已经被删除'
                    },
                    status_code=404
                )
                
        except Exception as e:
            current_app.logger.error(f"删除收藏失败: {str(e)}")
            return create_response(
                success=False,
                error={
                    'code': 'DELETE_FAVORITE_ERROR',
                    'message': '删除收藏失败',
                    'details': str(e) if current_app.debug else '服务异常'
                },
                status_code=500
            )
